package com.example.springboot.controller;

import com.example.springboot.constant.ResConstansts;
import com.example.springboot.entity.Post;
import com.example.springboot.entity.Res;
import com.example.springboot.entity.User;
import com.example.springboot.service.ESService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys_users")
public class SysUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ESService esService;
    private JwtUtil jwtUtil;
    private static final String appId ="wx82f682730a68404d";
    private static final String appSecret = "211def84008ec9f28198be28db29f680";
    private static final String WX_CODE2SESSION_URL =
            "https://api.weixin.qq.com/sns/jscode2session";
    @GetMapping("/{id}")
    public Res<User> getUserInfo(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return new Res<User>().data(user).msg("success").code(200);
    }
    @PostMapping("/changePassword/{userId}")
    public Res<User> changePassword(@PathVariable Integer userId,
                                    @RequestBody Map<String, String> payload,
                                    @RequestHeader(value = "Authorization", required = false) String token) {
        if (token == null)
            return new Res<User>().code(404).msg("未登录").data(null);
        String username = payload.get("username");
        String oldPassword = payload.get("oldPassword");
        String newPassword = payload.get("newPassword");
        try {
            String reqToken = token.substring(7);// 去掉 "Bearer " 前缀
            Integer visitId = jwtUtil.getUserIdByToken(reqToken);
            if (visitId != userId) {
                return ResConstansts.SERVICE_ERROR;
            } else {
                userService.changePassword(username,userId, oldPassword, newPassword);
                return new Res<User>().data(null).msg("success").code(200);
            }
        }catch (Exception e){
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }
    @PostMapping
    public Res<User> updateUserInfo(@RequestBody User user, @RequestHeader(value = "Authorization", required = false) String token) {
        if (token == null)
            return new Res<User>().code(404).msg("未登录").data(null);
        try {
            String reqToken = token.substring(7);
            Integer visitId = jwtUtil.getUserIdByToken(reqToken);
            System.out.println(visitId);
            System.out.println(user);
            if (visitId != user.getId()) {
                return ResConstansts.SERVICE_ERROR;
            } else {
                userService.updateUserInfo(user);
            }
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
        return new Res<User>().data(null).msg("success").code(200);
    }

    @GetMapping("/getCollectPost/{id}")
    public Res<List<Post>> getCollectPost(@PathVariable Integer id, @RequestParam Integer pageNum
//            , @RequestHeader(value = "Authorization", required = false) String token
    ) {
//        if (token == null)
//            return new Res<List<Post>>().code(404).msg("未登录").data(null);
        try {
//            String reqToken = token.substring(7);// 去掉 "Bearer " 前缀
//            Integer visitId=jwtUtil.getUserIdByToken(reqToken);
//            if(visitId!=id){
//                return ResConstansts.SERVICE_ERROR;
//            }else{
            List<Post> res = userService.getCollectPost(id, pageNum);
            return new Res<List<Post>>().data(res).msg("success").code(200);
//            }
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }

    @GetMapping("/getFollowPost/{id}")
    public Res<List<Post>> getFollowPost(@PathVariable Integer id, @RequestParam Integer pageNum
//            ,@RequestHeader(value = "Authorization", required = false) String token
    ) {
//        if (token == null)
//            return new Res<List<Post>>().code(404).msg("未登录").data(null);
        try {
//            String reqToken = token.substring(7);// 去掉 "Bearer " 前缀
//            Integer visitId=jwtUtil.getUserIdByToken(reqToken);
//            if(visitId!=id){
//                return ResConstansts.SERVICE_ERROR;
//            }else{
            List<Post> res = userService.getFollowPost(id, pageNum);
            return new Res<List<Post>>().data(res).msg("success").code(200);
//            }
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }

    @GetMapping("/getUserPost/{id}")
    public Res<List<Post>> getUserPost(@PathVariable Integer id, @RequestParam Integer pageNum) {
        try {
            List<Post> res = userService.getUserPost(id, pageNum);
            return new Res<List<Post>>().data(res).msg("success").code(200);
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }
    @GetMapping("/getCollectPostNum/{id}")
    public Res<Integer> getCollectPostNum(@PathVariable Integer id) {
        try {
            Integer res = userService.getCollectPostNum(id);
            return new Res<Integer>().data(res).msg("success").code(200);
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }
    @GetMapping("/getUserPostNum/{id}")
    public Res<Integer> getUserPostNum(@PathVariable Integer id) {
        try {
            Integer res = userService.getUserPostNum(id);
            return new Res<Integer>().data(res).msg("success").code(200);
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }
    @GetMapping("/search")
    public Res<List<User>> search(@RequestParam String searchContent,@RequestParam Integer orderType,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        if(searchContent==null){
            return new Res<List<User>>().code(404).msg("未输入搜索内容").data(null);
        }
        try {
            List<User> res = esService.getUser(searchContent,orderType,pageNum, pageSize);
            if(res!=null){
                return new Res<List<User>>().data(res).msg("success").code(200);
            }else{
                return ResConstansts.SERVICE_ERROR;
            }
        } catch (Exception e) {
            System.out.println(e);
            return ResConstansts.SERVICE_ERROR;
        }
    }
    @GetMapping("/wx")
    public Res<User> getUserInfoByWx(@RequestParam String code) throws JsonProcessingException {
       if (code == null || code.isEmpty()) {
            return new Res<User>().code(400).msg("参数错误");
        }
        String url = WX_CODE2SESSION_URL +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        // 解析微信返回的JSON数据
        String body = response.getBody();
        if (body != null && !body.isEmpty()) {
            Map<String, Object> result = new ObjectMapper().readValue(body, Map.class);

            // 检查返回结果
            if (result.containsKey("errcode")) {
                new Res<User>().code(500).msg("微信接口调用失败: " + result.get("errmsg"));
            }

            // 提取 openid 和 session_key
            String openid = (String) result.get("openid");
            String sessionKey = (String) result.get("session_key");

            // 根据需要保存到数据库或返回给前端
            User user = new User();
            user.setOpenId(openid);
            User res = userService.selectUserByOpenId(user);
            // 返回成功响应
            return new Res<User>().data(res).msg("success").code(200);
        } else {
            return new Res<User>().code(500).msg("微信接口调用失败");
        }
    }
}
